define(['wizard','monitorCert','monitorTool'] ,function (wizard ,monitorCert ,monitorTool){

	var index_monitor_id
	var index_monitor_type
	var index_monitor_type_name

	var index_asset_id
	var index_asset_name
	var index_asset_mainIp

	var index_monitor_name

	var el_monitor_info

	var step_5_edit

	var index_el

	var index_param_obj

	var rhTab

	var asset_list_header = [
								{text:'资产名称',name:"entityName",searchRender : function(el){
									el.append('<input type="text" search-data="entityName" class="form-control input-sm" />');
									el.append('<input type="hidden" search-data="monitorType" searchCache/>');
									el.find("[search-data=monitorType]").val($("[data-id=temp_type]").val());
								}},
								{text:'IP地址',name:"ipvAddress",align:"left",searchRender:function (el){
								  		index_render_div(el ,{type:"ip"});
								   }},
								{text:'资产类型',name:"entityType",searchRender : function (el){
								   	   assetTypeEl = $('<div class="inputdrop" id="entityType"></div>');
								   	   g_formel.sec_biz_render({
								   	   		assetTypeEl : assetTypeEl
								   	   });
								   	   el.append(assetTypeEl);
								   }},
								{text:'管控域',name:"securityName",searchRender : function (el){
								   	   secEl = $('<div class="inputdrop" id="securityName"></div>');
								   	   g_formel.sec_biz_render({
								   	   		secEl : secEl
								   	   });
								   	   el.append(secEl);
								   }}
							]

	return {
		init : function (el ,opt){
			var self = this
			self.reset()
			index_el = el
			el_monitor_info = el.find("[class=__monitor_info_right]")
			index_param_obj = index_query_param_get()
			var initParam = {
				step_array : [
								{name : "选择监控器类型" ,icon : "" ,description : "",render : function (cEl){
									__monitor_type_list_render(cEl)
								},validate : function (){
									index_monitor_type = rhTab.getSelectedId()
									if (!index_monitor_type)
										g_dialog.operateAlert(index_el ,"请选择监控器类型" ,"error")
									else
									{
										$("[data-id=temp_type]").val(index_monitor_type)
										index_monitor_type_name = rhTab.getSelectedName()
										return true
									}
								}},
								{name : "选择监控的资产" ,render : function (){
									__asset_list_render()
								},validate : function (){
									var data = g_grid.getData($("#asset_list_div") ,{chk:true})
									if (!data || data.length == 0)
										g_dialog.operateAlert(index_el ,"请选择被监控资产" ,"error")
									else
									{
										index_asset_id = data[0].edId
										index_asset_mainIp = data[0].ipvAddress
										index_asset_name = data[0].entityName
										return true
									}
								}} ,
								{name : "配置基本信息" ,render : function (cEl){
									__base_info_init(cEl)
								},validate : function (){
									if (g_validate.validate($("#base_info_div")))
										return true
								}},
								{name : "填写凭证信息" ,render : function (cEl){
									__cert_info_init(cEl.find("[class*=__info]"))
								},validate : function (){
									return monitorCert.validate()
								}} ,
								{name : "填写指标信息" ,render : function (cEl){
									// 给hidden 赋值
									__hidden_val_set()
									cEl.find("[class*=__info]").css("height" ,"auto")
									cEl.find("[class*=__info]").css("min-height" ,"350px")
									__quota_info_init(cEl.find("[class*=__info]"))
								}}
							 ],
				beforeRender : function (step){
					__monitor_info_render(step)
				},
				finish : function (){self.finish(el ,opt)}
			}
			if (index_param_obj.monitorId){
				index_monitor_id = index_param_obj.monitorId
				um_ajax_get({
					url : "monitorConfig/queryMonitorDetail",
					paramObj : {"monitorId":index_param_obj.monitorId,"deviceSource":null,"monitorType":index_param_obj.monitorType,
								"edId":index_param_obj.edId,"intsStatus":index_param_obj.intsStatus,"regionId":""},
					maskObj : "body",
					successCallBack : function (data) 
					{
						step_5_edit = data
						index_monitor_type = step_5_edit.monitorStore[0].monitorType
						index_monitor_type_name = step_5_edit.monitorStore[0].monitorTypeName
						index_asset_name = step_5_edit.monitorStore[0].entityName
						index_asset_mainIp = step_5_edit.monitorStore[0].ipvAddress
						index_monitor_name = step_5_edit.monitorStore[0].monitorName
						wizard.init(el ,initParam)
						wizard.finish_set(0)
						wizard.step_show(1)
					}
				});
			}
			else{
				// 从资产页面带过来的话
				if (opt.assetObj)
				{
					initParam.step_array.splice(1,1)
					$(".asset_info_title").show()
					$("#asset_list_div").remove()
					$(".__monitor_info_right").css("top" ,"140px")
					$("#asset_info_title_name").text(opt.assetObj.name)
					$("#asset_info_title_ip").text(opt.assetObj.ip)
					$("#asset_info_title_systemName").text(opt.assetObj.systemName)
					index_asset_mainIp = '123.123.123.123'
					index_asset_id = opt.assetObj.id
					index_asset_name = opt.assetObj.name
					index_asset_mainIp = opt.assetObj.ip
				}
				wizard.init(el ,initParam)
				wizard.step_show(0)
			}
		},
		reset : function (){
			index_monitor_id = ""
			index_monitor_type = ""
			index_asset_id = ""
			index_asset_name = ""
			index_asset_mainIp = ""
			index_monitor_name = ""
			step_5_edit = null
			index_el = null
		},
		finish : function (el ,opt){
			if (el.find("[id=detail_store_form]") && !g_validate.validate(el.find("[id=detail_store_form]"))) 
			{
				g_dialog.operateAlert(el,"请完善信息。","error");
				return;
			}
			/*封装monitorGroupStore*/
			var monitorGroupStore = el.find("#base_info_div").umDataBind("serialize");
			monitorGroupStore.monitorType = index_monitor_type
			monitorGroupStore.monitorMemo = monitorGroupStore.remark
			monitorGroupStore.pollDateText = el.find("[data-id=pollDate]").val()
			monitorGroupStore.notMonitoredEntityDevice = index_asset_id
			monitorGroupStore.groupId = index_monitor_id?index_monitor_id:""
			step_5_edit && (monitorGroupStore.monitorAgent = step_5_edit.monitorAgent)
			step_5_edit && (monitorGroupStore.deviceSource = step_5_edit.monitorDeviceStore[0].deviceSource)

			/* 封装凭证信息**/
			var certStore = monitorCert.save()

			/*封装第五步表单信息*/
			var monitorDetailStore = el.find("[id=detail_store_form]") && el.find("[id=detail_store_form]").umDataBind("serialize")
			!monitorDetailStore && (monitorDetailStore = {})
			monitorDetailStore.connectType = (certStore[0]?certStore[0].connectType:"")
			monitorDetailStore.opFlag = step_5_edit ? "upd" : "add"
			monitorDetailStore.monitorId = step_5_edit ? step_5_edit.monitorStore[0].monitorId : ""

			var param = __create_param_obj(monitorGroupStore ,certStore ,monitorDetailStore ,index_el)

			um_ajax_post({
							url : step_5_edit ? "monitorConfig/updMonitorGroup" : "monitorConfig/addMonitorGroup",
							paramObj : param,
							maskObj : "body",
							successCallBack : function(data) 
							{
								g_dialog.operateAlert(null ,"数据提交成功!")
								opt.submitCbf && opt.submitCbf()
							}
						});
		}
	}

	function __monitor_type_list_render(cEl){
		um_ajax_get({
			url : "deviceMonitor/queryMonitorClassAndTypeList",
			paramObj : {},
			isLoad : true,
			successCallBack : function (data){
				var obj = monitor_type_first_get(data)
				rhTab = new RhTab(index_el.find("[data-type=rhTab]") ,{
					ul_data : obj.firstList,
					data : obj.monitorTypeObj,
					right_click : function (val ,name){
						if (index_monitor_type && (index_monitor_type != val) ){
							g_dialog.operateConfirm("变更监控器类型会重置后面的表单，确定变更吗？" ,{
								width : "350px",
								saveclick : function() 
								{
									wizard.step_reset(1)
									wizard.step_reset(2)
									wizard.step_reset(3)
									wizard.step_reset(4)
								}
							});
						}
					}
				})

				rhTab.init(index_monitor_type)
				if (index_monitor_type){
					cEl.find("[class*=__info]").addClass('prel')
					cEl.find("[class*=__info]").append('<div class="mask"></div>')
				}	
			}
		})

		function monitor_type_first_get(data){
			var obj = new Object()
			var monitorTypeObj = new Object()
			var firstList = []
			for (var i = 0; i < data.length; i++) {
				firstList.push(data[i][0])
				monitorTypeObj[data[i][0].label] = data[i].slice(1)
			}
			obj.firstList = firstList
			obj.monitorTypeObj = monitorTypeObj
			return obj
		}
	}

	function __asset_list_render(){
		var el_asset_list_div = index_el.find("#asset_list_div")
		g_grid.render(el_asset_list_div ,{
			url:"monitorConfig/queryNoMonitoreDeviceList",
			header:asset_list_header,
			paramObj : {monitorType:index_monitor_type ,queryTag:"query"},
			paginator : false,
			hideSearch : true,
			checkType : "radio",
			cbf : function (){
				if (step_5_edit){
					var data = g_grid.getData(el_asset_list_div)
					var tmp = 0
					var flag = false
					var tmp_obj = _.find(data ,function (obj){
						tmp++
						return flag = (obj.edId == step_5_edit.monitorStore[0].edId)
					})

					if (flag)
					{
						var trObj = g_grid.getTrObj(el_asset_list_div ,{index:tmp-1})
						trObj.find("[name=grid_check_type]").attr("checked" ,"checked")
						if (tmp != 1)
						{
							var firstTrObj = g_grid.getTrObj(el_asset_list_div ,{index:0})
							firstTrObj.before(trObj)
						}
					}
					else
					{
						g_grid.addData(el_asset_list_div,[step_5_edit.monitorStore[0]])
						var trObj = g_grid.getTrObj(el_asset_list_div ,{index:data.length})
						trObj.find("[name=grid_check_type]").attr("checked" ,"checked")
						var firstTrObj = g_grid.getTrObj(el_asset_list_div ,{index:0})
						firstTrObj.before(trObj)
					}

				}
			}
		})
	}

	function __base_info_init(cEl){
		um_ajax_html({
			url : "js/plugin/monitor/monitor.html",
			selector : "#monitor_config_base_info_template",
			successCallBack : function (tEl){
				index_el.find("#base_info_div").html(tEl.html())
				index_form_init(index_el.find("#base_info_div"))
				__proxy_server_render(cEl)
			}
		})
	}

	function __proxy_server_render(cEl){
		um_ajax_get({
			url : "monitorConfig/queryMonitorAgent",
			isLoad : false,
			successCallBack : function (data) 
			{
				for (var i = 0; i < data.length; i++) {
					index_el.find("[data-id=monitorAgent]").append('<option name="monitorAgent" value="'
									+data[i].agentId+'">'+data[i].agentName+'</option>')
				}
				if (step_5_edit)
				{
					var eData = step_5_edit.monitorStore[0];
					eData.status = eData.monitorManageStatus;
					cEl.find("[data-id=groupName]").val(eData.monitorName);
					cEl.find("[data-id=monitorAgent]").attr("disabled","disabled");
					cEl.find("[id=base_info_div]").umDataBind("render" ,eData);
					cEl.find("[data-id=remark]").val(eData.monitorMemo);
				}
				cEl.find("select").trigger("change");

				cEl.find("[data-id=groupName]").change(function (){
					index_monitor_name = $(this).val()
				})
				cEl.find("[data-id=groupName]").change()
			}
		})
	}

	function __cert_info_init(cEl){
		cEl.css("height" ,"auto")
		var initData = step_5_edit?step_5_edit.monitorStore[0]:null
		monitorCert.init(cEl ,index_monitor_type ,
						index_asset_id ,index_asset_mainIp ,
						index_el.find("[data-id=monitorAgent]").val(),initData)
	}

	function __quota_info_init(cEl){
		um_ajax_html({
			url : "tpl/monitor_config/" + index_monitor_type + ".html",
			successCallBack : function (data){
				cEl.html(data)
				var param = null
				step_5_edit && (param = {detail:step_5_edit})
				monitorTool[index_monitor_type + '_init'](cEl ,param)
				/*第五步中的测试配置按钮*/
				$("body").off('.monitor');
				$("body").on("click.monitor" ,"[data-type=test_btn_in_step5]" ,function (){
				//cEl.find("[data-type=test_btn_in_step5]").click(function(){
					var obj = monitorTool[index_monitor_type+"_step5_test"] && monitorTool[index_monitor_type+"_step5_test"](index_el ,cEl)
					um_ajax_post({
						url : "monitorConfig/doTest",
						paramObj : obj,
						maskObj : "body",
						successCallBack : function (data){
							g_dialog.dialog('<div class="p10" id="test_alert"></div>' ,{
								width : "400px",
								title : "测试结果",
								isDetail : true,
								init : function(el){
									el.find("[id=test_alert]").html(data.teststore && data.teststore.length > 0 && data.teststore[0].result);
								}
							});
						}
					});
				});
			}
		})
	}

	function __create_param_obj(monitorGroupStore ,certStore ,monitorDetailStore ,el){
		var param = {}
		switch (index_monitor_type)
		{
			case "ORACLE":
					var dStore = g_grid.getData(el.find("[data-id=database-nu]"));
					if (dStore.length == 0) 
					{
						g_dialog.operateAlert(el ,"	请至少配置一个实例信息。" ,"error");
						return false;
					}
					for (var i = 0; i < dStore.length; i++) {
						dStore[i].opFlag = step_5_edit ? "upd" : "add";
						dStore[i].currentType = "-1";
						dStore[i].configStatus = "2";
						if (dStore[i].openAlarm == 0) 
						{
							dStore[i].connectType = -1;
						}
						delete dStore[i].openAlarm;
						dStore[i].tsvalues = $("[data-id=temp_table_space]").val();
						dStore[i].unTsvalues = $("[data-id=temp_not_table_space]").val();
						dStore[i].hostFileBaseLineDataStore = $("[data-btn=setFileBaseLineHidden]").eq(i).data("data");
					}
					monitorGroupStore.instStatus = 1;
					param = {
								monitorGroupStore:monitorGroupStore,
								certStore:certStore,
								monitorDetailStore:dStore
							}
					break;
			case "SQLSERVER":
					var dStore = g_grid.getData(el.find("[data-id=database-nu]"));
					if (dStore.length == 0) 
					{
						g_dialog.operateAlert(null ,"请至少配置一个实例信息。" ,"error");
						return false;
					}
					for (var i = 0; i < dStore.length; i++) {
						dStore[i].opFlag = step_5_edit ? "upd" : "add";
						dStore[i].connectType = -1;
						dStore[i]["_t"] = "1";
						dStore[i].version = $("[data-id=version]").val();
						delete dStore[i].check_all;
						delete dStore[i].check_inp;
					} 
					monitorGroupStore.instStatus = 1;
					monitorGroupStore.monitorName = monitorGroupStore.groupName;
					monitorGroupStore.monitorManageStatus = monitorGroupStore.status;
					param = {
						monitorDetailStore : dStore,
						certStore:certStore,
						monitorGroupStore : monitorGroupStore
					};
					break;
			case "LINUX":
					var monitorFaultGridStore = g_grid.getData(el.find("[id=grid-u]"));
					var monitorPerformGridStore = g_grid.getData(el.find("[id=grid-al]"));
					var monitorUnPerformGridStore = g_grid.getData(el.find("[id=grid-ar]"));
					// return;
					for (var h = 0; h < monitorFaultGridStore.length; h++) {
						monitorFaultGridStore[h]._s = false;
						monitorFaultGridStore[h]._t = 1;
						monitorFaultGridStore[h].faultId = "1202003";
					}
					for (var k = 0; k < monitorPerformGridStore.length; k++) {
						//monitorPerformGridStore[k].lastTime = "3992";
						monitorPerformGridStore[k].performId = "1102003";
					}
					for (var l = 0; l < monitorUnPerformGridStore.length; l++) {
						//monitorUnPerformGridStore[l].lastTime = "100";
						monitorUnPerformGridStore[l].performId = "1102003";
					}
					monitorGroupStore.instStatus = 0;
					param = 
						{
							"monitorDetailStore": monitorDetailStore,
							"monitorFaultGridStore": monitorFaultGridStore,
							"monitorGroupStore": monitorGroupStore,
							"certStore":certStore,
							"monitorPerformGridStore": monitorPerformGridStore,
							"monitorUnPerformGridStore": monitorUnPerformGridStore,
							"hostProcessBaseLineDataStore": $("[data-btn=setProcessBaseLine]").data("data"),
							"hostPortBaseLineDataStore": $("[data-btn=setPortBaseLine]").data("data"),
							"hostDiskBaseLineDataStore": $("[data-btn=setDiskBaseLine]").data("data")
						};
					break;
			case "MYSQL":
					monitorGroupStore.instStatus = 0;
					param = 
						{
							"monitorDetailStore" : monitorDetailStore,
							"monitorGroupStore" : monitorGroupStore
						};
					break;
			case "WINDOWS":
					var monitorFaultGridStore = g_grid.getData(el.find("[id=grid-u]"));
					var monitorPerformGridStore = g_grid.getData(el.find("[id=grid-al]"));
					var monitorUnPerformGridStore = g_grid.getData(el.find("[id=grid-ar]"));
					// return;
					for (var h = 0; h < monitorFaultGridStore.length; h++) {
						monitorFaultGridStore[h]._s = false;
						monitorFaultGridStore[h]._t = 1;
						monitorFaultGridStore[h].faultId = "1202003";
					}
					for (var k = 0; k < monitorPerformGridStore.length; k++) {
						monitorPerformGridStore[k].lastTime = "3992";
						monitorPerformGridStore[k].performId = "1102003";
					}
					for (var l = 0; l < monitorUnPerformGridStore.length; l++) {
						monitorUnPerformGridStore[l].lastTime = "100";
						monitorUnPerformGridStore[l].performId = "1102003";
					}
					monitorGroupStore.instStatus = 0;
					param = 
						{
							"monitorDetailStore": monitorDetailStore,
							"monitorFaultGridStore": monitorFaultGridStore,
							"monitorGroupStore": monitorGroupStore,
							"certStore":certStore,
							"monitorPerformGridStore": monitorPerformGridStore,
							"monitorUnPerformGridStore": monitorUnPerformGridStore,
							"hostProcessBaseLineDataStore": $("[data-btn=setProcessBaseLine]").data("data"),
							"hostPortBaseLineDataStore": $("[data-btn=setPortBaseLine]").data("data"),
							"hostDiskBaseLineDataStore": $("[data-btn=setDiskBaseLine]").data("data")
						};
					break;
			case "NETEYE_FIREWALL":
					monitorGroupStore.instStatus = 0;
					param = {
						"monitorDetailStore" : monitorDetailStore,
						"monitorGroupStore" : monitorGroupStore,
						"certStore" : certStore
					};
					break;
			case "COMMON_URL":
					var el_url_table = el.find("[data-id=url_table]");
					var trObjArray = g_grid.getTrObj(el_url_table);

					var monitorDetailStore = [];
					var monitorPerformGridStore = [];
					var monitorFaultGridStore = [];
					var monitorParamGridStore = [];


					trObjArray.each(function (){
						monitorDetailStore.push($(this).data("monitorDetailStore"));
						monitorPerformGridStore.push($(this).data("monitorPerformGridStore"));
						monitorFaultGridStore.push($(this).data("monitorFaultGridStore"));
						monitorParamGridStore.push($(this).data("monitorParamGridStore"));
					});

					monitorGroupStore.instStatus = 0;
					param = {
						monitorDetailStore : monitorDetailStore,
						monitorGroupStore : monitorGroupStore,
						monitorPerformGridStore : monitorPerformGridStore,
						monitorFaultGridStore : monitorFaultGridStore,
						monitorParamGridStore : monitorParamGridStore,
						monitorDeleteUrlStore : el_url_table.data("deleteArray").join(","),
						proofId:el_url_table.data("proofId")
					};
					break;
			case "NGINX":
					monitorGroupStore.instStatus = 0;
					param = 
						{
							"monitorDetailStore" : monitorDetailStore,
							"monitorGroupStore" : monitorGroupStore
						};
					break;
			case "TOMCAT":
					var urlList = [];
					for (var i = 0; i < g_grid.getData(el.find("#grid-he")).length; i++) {
						var obj = {urlAddress:g_grid.getData(el.find("#grid-he"))[i].urlAddress,_t:"1",_s:"false"};
						urlList.push(obj);
					}

					monitorGroupStore.instStatus = 0;
					param = {
						monitorGroupStore:monitorGroupStore,
						monitorDetailStore:monitorDetailStore,
						urlStore:urlList
					};
					break;
			case "PORT_MONITOR":
					monitorGroupStore.instStatus = 0;
					param = {
						monitorGroupStore : monitorGroupStore,
						monitorDetailStore : monitorDetailStore
					};
					break;
			case "NE_HUAWEI":
					monitorDetailStore.arpFlag = el.find("[data-id=arpFlag]:checked").length > 0 ? "1" :"0";
					monitorDetailStore.rcCmd = el.find("[data-id=rcCmd]:checked").length > 0 ? "1" :"0";
					monitorDetailStore.scCmd = el.find("[data-id=scCmd]:checked").length > 0 ? "1" :"0";
					monitorGroupStore.instStatus = 0;
					param = {
						"monitorDetailStore" : monitorDetailStore,
						"monitorGroupStore" : monitorGroupStore,
						"certStore" : certStore
					};
					break;
			case "H3C":
					monitorDetailStore.arpFlag = el.find("[data-id=arpFlag]:checked").length > 0 ? "1" :"0";
					monitorDetailStore.dbPass = el.find("[data-id=dbPass]:checked").length > 0 ? "1" :"0";
					monitorDetailStore.dbUser = el.find("[data-id=dbUser]:checked").length > 0 ? "1" :"0";
					for (var i = 0; i < certStore.length; i++) {
						certStore[i].connectType = certStore[i].connectType.split(",")[0];
					}
					monitorGroupStore.instStatus = 0;
					param = {
						"monitorDetailStore" : monitorDetailStore,
						"monitorGroupStore" : monitorGroupStore,
						"certStore" : certStore
					};
					break;
			case "APACHE":
					urlStore = g_grid.getData(el.find("[id=grid-he]"));
					monitorGroupStore.instStatus = 0;
					param = {
						"monitorDetailStore" : monitorDetailStore,
						"monitorGroupStore" : monitorGroupStore,
						"urlStore" : urlStore
					};
					break;
		}
		return param
	}

	// 给hidden元素赋值
	function __hidden_val_set(){
		index_el.find("[data-id=temp_type]").val(index_monitor_type)
		index_el.find("[data-id=temp_monitored_asset]").val(index_asset_id)
		index_el.find("[data-id=connectType]").val(monitorCert.get_cert_type())
	}

	function __monitor_info_render(step){
		if (step == 0){
			el_monitor_info.hide()
			return false
		}
		el_monitor_info.find("#__type").text(index_monitor_type_name)
		el_monitor_info.find("#__monitor_name").text(index_monitor_name)
		el_monitor_info.find("#__asset_ip").text(index_asset_mainIp)
		el_monitor_info.find("#__asset_name").text(index_asset_name)
		
		el_monitor_info.show()
	}
})